package com.itheima.bigevent.service.impl;

import com.itheima.bigevent.mapper.UserMapper;
import com.itheima.bigevent.pojo.User;
import com.itheima.bigevent.service.UserService;
import com.itheima.bigevent.utils.Md5Util;
import com.itheima.bigevent.utils.ThreadLocalUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.regex.Pattern;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;
    @Override
    public User findByUsername(String username) {
        return userMapper.findByUserName(username);
    }

    @Transactional
    @Override
    public boolean register(String username, String password) {
        // 查询当前用户名是否已有用户
        User user = this.findByUsername(username);
        if (user == null || user.getId() == null) {
            // 用户名未被占用
            String md5String = Md5Util.getMD5String(password);
            int register = userMapper.register(username, md5String);
            return register > 0;
        }else {
            // 用户名已被占用
            return false;
        }
    }

    @Override
    public void update(User user) {
        // 设置更新时间为当前
        user.setUpdateTime(LocalDateTime.now());
        userMapper.update(user);
        // 更新ThreadLocal内的用户信息
        ThreadLocalUtil.set(user);
    }

    @Override
    public void updateAvatar(String avatarUrl) {
        // 获取当前用户的信息
        User currentUser = ThreadLocalUtil.get();
        userMapper.updateAvatar(avatarUrl, currentUser.getId());
    }

    @Override
    public void updatePwd(String newPwd) {
        // 获取当前用户信息
        User currentUser = ThreadLocalUtil.get();
        userMapper.updatePwd(Md5Util.getMD5String(newPwd), currentUser.getId());
    }
}
